// SMUserTradeListViewController.m
#import "SMUserTradeListViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "SMTradeCell.h"
#import "SMTradeItem.h"
#import "SMAPIClient.h" // ✅ 记得引入网络层

@interface SMUserTradeListViewController ()
@property(nonatomic, copy) NSString *uid;
@property(nonatomic, assign) SMUserTradeListType type;
@property(nonatomic, strong) NSMutableArray<SMTradeItem*> *data;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL hasMore;
@end

@implementation SMUserTradeListViewController

- (instancetype)initWithUserId:(NSString *)uid type:(SMUserTradeListType)type {
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        _uid = [uid copy];
        _type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:SMTradeCell.class forCellReuseIdentifier:@"cell"];

    self.data = [NSMutableArray array];
    self.page = 1; self.hasMore = YES;

    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Paging
- (void)refresh {
    self.page = 1;
    self.hasMore = YES;
    [self requestPage:self.page];
}

- (void)loadMore {
    if (self.hasMore) {
        self.page++;
        [self requestPage:self.page];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Networking (with fallback)
- (void)requestPage:(NSInteger)page {
    NSString *kind = (self.type == SMUserTradeListTypeSupply) ? @"supply" : @"demand";
    NSString *path = [NSString stringWithFormat:@"user/%@/trade/%@", self.uid ?: @"0", kind];
    NSDictionary *params = @{@"page":@(page), @"pageSize":@(10)};

    __weak typeof(self) weakSelf = self;
    [[SMAPIClient shared] GET:path parameters:params success:^(id json) {
        NSArray *arr = nil;
        if ([json isKindOfClass:NSDictionary.class] && [json[@"data"] isKindOfClass:NSArray.class]) {
            arr = json[@"data"];
        } else if ([json isKindOfClass:NSArray.class]) {
            arr = (NSArray *)json;
        }
        if (!arr) {
            [weakSelf applyData:[weakSelf fallbackPage:page] page:page];
            return;
        }
        NSMutableArray *parsed = [NSMutableArray array];
        for (NSDictionary *d in arr) {
            if (![d isKindOfClass:NSDictionary.class]) continue;
            SMTradeItem *it = [SMTradeItem new];
            it.itemId   = [NSString stringWithFormat:@"%@", d[@"id"] ?: [[NSUUID UUID] UUIDString]];
            it.title    = d[@"title"] ?: @"标题";
            it.detail   = d[@"detail"] ?: @"";
            it.price    = [d[@"price"] isKindOfClass:NSString.class] ? d[@"price"] : [d[@"price"] stringValue];
            it.city     = d[@"city"] ?: @"";
            it.imageURL = d[@"image"] ?: @"";
            NSNumber *ts = d[@"updated_at"];
            if (ts) {
                NSTimeInterval v = [ts doubleValue];
                if (v > 1000000000000) v /= 1000.0; // 兼容毫秒
                it.updatedAt = [NSDate dateWithTimeIntervalSince1970:v];
            } else {
                it.updatedAt = [NSDate date];
            }
            [parsed addObject:it];
        }
        [weakSelf applyData:parsed page:page];
    } failure:^(NSError *error) {
        [weakSelf applyData:[weakSelf fallbackPage:page] page:page];
    }];
}

- (NSArray<SMTradeItem *> *)fallbackPage:(NSInteger)page {
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        SMTradeItem *it = [SMTradeItem new];
        it.itemId = [NSString stringWithFormat:@"%@-%@-%ld-%d",
                     self.uid ?: @"u",
                     (self.type == SMUserTradeListTypeSupply ? @"S" : @"D"),
                     (long)page, i];
        it.title = [NSString stringWithFormat:@"%@ · #%d",
                    (self.type == SMUserTradeListTypeSupply ? @"出售" : @"求购"), i+1];
        it.detail = (self.type == SMUserTradeListTypeSupply)
                    ? @"重废/剪切料，规格稳定，量大出货，支持上门验货。"
                    : @"长期求购工厂下脚料，品质优先，价格面议。";
        it.price = [NSString stringWithFormat:@"%d", 1800 + arc4random_uniform(800)];
        it.city = @[@"苏州",@"上海",@"天津",@"成都",@"佛山"][arc4random_uniform(5)];
        it.imageURL = [NSString stringWithFormat:@"https://picsum.photos/seed/usert_%@_%ld_%d/520/360",
                       self.uid ?: @"u",(long)page,i];
        it.updatedAt = [NSDate dateWithTimeIntervalSinceNow:-(arc4random_uniform(4*24*3600))];
        [arr addObject:it];
    }
    return arr;
}

- (void)applyData:(NSArray<SMTradeItem*>*)arr page:(NSInteger)page {
    if (page == 1) [self.data removeAllObjects];
    [self.data addObjectsFromArray:arr];
    self.hasMore = arr.count >= 10;

    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    if (self.hasMore) [self.tableView.mj_footer endRefreshing];
    else [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

#pragma mark - Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.data.count; }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 116; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMTradeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell configure:self.data[indexPath.row]];
    return cell;
}

@end
